package com;

import com.service.SysDictionaryService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Map;

@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.mapper")
@EnableCaching
public class HappyApplication {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);//这两句不加不能跨域上传文件，
        corsConfiguration.setMaxAge(3600l);//加上去就可以了
        return corsConfiguration;
    }

    /**
     * 跨域过滤器
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(HappyApplication.class, args);
        run.addApplicationListener(e -> {
            SysDictionaryService dictionaryService = (SysDictionaryService) run.getBean("SysDictionaryService");
            Map<String, Map<String, String>> data = dictionaryService.load();
            if (dictionaryService.getData().size() == 0) {
                dictionaryService.setData(data);
            }
        });
    }

}
